//
//  BISafeVC.m
//  BIProjectModule
//
//  Created by yown on 2022/2/9.
//

#import "BISafeVC.h"

#import <BIToolModule/BIAlertAction.h>
#import <BIToolModule/NSObject+HUD.h>
#import <Masonry/Masonry.h>

@interface BISafeVC ()

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation BISafeVC

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self bi_setupView];
    [self bi_setupLayout];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self bi_showAlert];
}

#pragma mark - Setup

- (void)bi_setupView {
    self.view.backgroundColor = [UIColor whiteColor];
    self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"launch_image@3x.png"]];
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.imageView];
}

- (void)bi_setupLayout {
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}

#pragma mark - Alert

- (void)bi_showAlert {
    [BIAlertAction showAlertOrActionSheet:UIAlertControllerStyleAlert title:@"提示" message:@"检测到应用可能已损坏，是否尝试修复？" actions:@[@"修复"] clickActionBlock:^(NSUInteger index) {
        // 显示加载中的菊花
        [self showActivityHUDWithTitle:@"修复中..."];
        // 修复函数
        [self bi_onBootingProtection];
        // 5s后结束
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 隐藏菊花
            [self hideActivityHUD];
            [self bi_fixFinish];
        });
    }];
}

#pragma mark - Private Method

/// 修复逻辑，如删除文件
- (void)bi_onBootingProtection {
    // 删除URL缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    // 清空沙盒
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *libraryDirectory = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    NSString *cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSArray *filePathsToRemove = @[documentsDirectory, libraryDirectory, cachesDirectory];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    for (NSString *filePath in filePathsToRemove) {
        if ([fileMgr fileExistsAtPath:filePath]) {
            NSArray *subFileArray = [fileMgr contentsOfDirectoryAtPath:filePath error:nil];
            for (NSString *subFileName in subFileArray) {
                NSString *subFilePath = [filePath stringByAppendingPathComponent:subFileName];
                [fileMgr removeItemAtPath:subFilePath error:nil];
            }
        }
    }
}

- (void)bi_fixFinish {
    // 提示修复完成
    [BIAlertAction showAlertOrActionSheet:UIAlertControllerStyleAlert title:@"提示" message:@"修复完成，请重新启动App" actions:@[@"完成"] clickActionBlock:^(NSUInteger index) {
        exit(0);
    }];
}

@end
